﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    class QuickImageButton : Button
    {
        public QuickImageButton(string fullPath, BitmapImage bi)
        {
            this.Style = TryFindResource("LSquareButtonStyle") as Style;
            this.Margin = new Thickness(5);
            this.Content = image;

            RegexOptions options = RegexOptions.None;
            options |= RegexOptions.IgnoreCase;
            options |= RegexOptions.Singleline;

            var reg = new Regex(@"\d{1,2}(?=\.png$)", options);

            var match = reg.Match(fullPath);

            if (match != null && match.Success)
            {
                if (int.TryParse(match.Value, out int result))
                {
                    if (result <= 24)
                    {
                        image.Height = image.Width = result;
                    }
                    else
                    {
                        image.Height = image.Width = 24;   // 最大 24
                    }
                }
            }

            this.fullPath = fullPath;
            image.Source = bi;

            var workspaceImagePath = Globals.PathofWorkspaceImages.ToLower();
            var lowerPath = this.fullPath.ToLower();
            if (lowerPath.StartsWith(workspaceImagePath))
            {
                this.relativePath = this.fullPath.Substring(workspaceImagePath.Length).Replace("\\", "/");
            }
            else
            {
                this.relativePath = "<错误路径>";
            }

            this.ToolTip = this.relativePath;

            this.Height = this.Width = 48;
            this.Click += QuickImageButton_Click;
        }

        private void QuickImageButton_Click(object sender, RoutedEventArgs e)
        {
            var ate = Globals.MainWindow.ActiveTextEditor;
            if (ate == null) return;

            ate.SelectedText = $"(:{this.RelavitePath}:)";
            ate.Select(ate.SelectionStart + ate.SelectionLength, 0);

            ate.Focus();
        }

        private Image image = new Image();

        private string fullPath;
        /// <summary>
        /// 文件在磁盘上的绝对路径。
        /// </summary>
        public string FullPath
        {
            get { return this.fullPath; }
        }

        private string relativePath;
        /// <summary>
        /// 假设文件路径是：“工作区根目录\Images~\0\1\a.png”。
        /// 则此属性值应为：“0\1\a.png”。
        /// </summary>
        public string RelavitePath
        {
            get
            {
                return this.relativePath;
            }
        }
    }
}
